package org.ofbiz.wvtools;
import java.sql.Timestamp;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Locale;
import java.util.Map;

import org.ofbiz.base.crypto.HashCrypt;
import org.ofbiz.base.util.Debug;
import org.ofbiz.base.util.UtilDateTime;
import org.ofbiz.base.util.UtilMisc;
import org.ofbiz.base.util.UtilProperties;
import org.ofbiz.base.util.UtilValidate;
import org.ofbiz.entity.Delegator;
import org.ofbiz.entity.GenericEntityException;
import org.ofbiz.entity.GenericValue;
import org.ofbiz.entity.util.EntityQuery;
import org.ofbiz.entity.util.EntityUtil;
import org.ofbiz.service.DispatchContext;
import org.ofbiz.service.GenericServiceException;
import org.ofbiz.service.LocalDispatcher;
import org.ofbiz.service.ModelService;
import org.ofbiz.service.ServiceUtil;

import javolution.util.FastList;


public class CoCompanyServices {
	public static final String module = CoCompanyServices.class.getName();
    public static final String resource = "WvtoolsUiLabels";
    public static final String resourceError = "WvtoolsUiLabels";
    
    public static  Map<String,Object> getOwnerPartyId(DispatchContext ctx, Map<String, ? extends Object> context){//(Map<String, ? extends Object> context) {
    	Map<String,Object> result = ServiceUtil.returnSuccess();
    	
		Delegator delegator = ctx.getDelegator();
        String partyId = (String) context.get("partyId");
        
        if (UtilValidate.isEmpty(partyId)) {
            GenericValue userLogin = (GenericValue) context.get("userLogin");
            if (userLogin != null) {
                partyId = userLogin.getString("partyId");
            }
        }
        try {
        if (UtilValidate.isNotEmpty(partyId)) {
        	
        	GenericValue person =delegator.findOne("Person", true, UtilMisc.toMap("partyId", partyId));
        	String companyId =person.getString("companyId");
        	result.put("companyId", companyId);
        	
        	String ownerPartyId =getTopCompanyId(delegator,companyId);
        	result.put("ownerPartyId", ownerPartyId);
        }
        } catch (GenericEntityException e) {
			Debug.logError(e.getMessage(), module);
			return ServiceUtil.returnError(e.getMessage());
		}
        
        return result;
    }
    
    private static String getTopCompanyId(Delegator delegator,String companyId) throws GenericEntityException{
    	
    	GenericValue person = delegator.findOne("PartyGroup", true, UtilMisc.toMap("partyId", companyId));
    	if (UtilValidate.isNotEmpty(person)&&UtilValidate.isNotEmpty(person.get("parentId"))) {
    		
    		String parentId =person.getString("parentId");
            if("_NA_".equals(parentId)) {
            	return companyId;
    		}
    		return getTopCompanyId(delegator,parentId);
    	}
    	return companyId;
    }
    
    /*
	 * create createSysCompany
	 */
	public static  Map<String,Object> createSysCompany(DispatchContext ctx, Map<String, ? extends Object> context){
		Debug.log("createSysCompany   === start");
		Map<String,Object> result = ServiceUtil.returnSuccess(ModelService.RESPOND_SUCCESS);
		Delegator delegator = ctx.getDelegator();
        try {
        	String partyId = delegator.getNextSeqId("Party");
        	GenericValue party = delegator.makeValue("Party", UtilMisc.toMap("partyId", partyId));
        	party.set("partyTypeId", "PARTY_GROUP");
        	party.create();
        	GenericValue partyRole = delegator.makeValue("PartyRole", UtilMisc.toMap("partyId", partyId));
        	partyRole.set("roleTypeId", "INTERNAL_ORGANIZATIO");
        	partyRole.create();
        	
        	GenericValue partyGroup = delegator.makeValue("PartyGroup", UtilMisc.toMap("partyId", partyId));
            partyGroup.setNonPKFields(context);
            if(UtilValidate.isEmpty(context.get("parentId"))){
                partyGroup.set("parentId", "_NA_");
            }
            String statusId = "PARTY_ENABLED";
            partyGroup.set("statusId", statusId);
            partyGroup.create();
			
			Debug.log("createSysCompany   === end");
			result.put("partyId", partyId);
	       
		} catch (GenericEntityException e) {
			Debug.logError(e.getMessage(), module);
			return ServiceUtil.returnError(e.getMessage());
		}
		return result;
	}
	/*
	 * update updateSysCompany
	 */
	public static  Map<String,Object> updateSysCompany(DispatchContext ctx, Map<String, ? extends Object> context){
		Debug.log("updateSysCompany   === start");
		Map<String,Object> result = ServiceUtil.returnSuccess(ModelService.RESPOND_SUCCESS);
		Delegator delegator = ctx.getDelegator();
        try {
        	String partyId = (String) context.get("partyId");
        	GenericValue partyGroup = EntityQuery.use(delegator).from("PartyGroup").where("partyId", partyId).queryOne();

            partyGroup.setNonPKFields(context);
            partyGroup.store();
			
			Debug.log("updateSysCompany   === end");
			result.put("partyId", partyId);
		} catch (GenericEntityException e) {
			Debug.logError(e.getMessage(), module);
			return ServiceUtil.returnError(e.getMessage());
		}
		return result;
	}
	
	/*
	 * update updateSysCompany
	 */
	public static  Map<String,Object> removeSysCompany(DispatchContext ctx, Map<String, ? extends Object> context){
		Debug.log("removeSysCompany   === start");
		Map<String,Object> result = ServiceUtil.returnSuccess( ModelService.RESPOND_SUCCESS);
		Delegator delegator = ctx.getDelegator();
        try {
        	String partyId = (String) context.get("partyId");
        	GenericValue partyGroup = EntityQuery.use(delegator).from("PartyGroup").where("partyId", partyId).queryOne();

        	String statusId = "PARTY_DISABLED";
        	partyGroup.set("statusId", statusId);
            partyGroup.store();
			
			Debug.log("removeSysCompany   === end");
			result.put("partyId", partyId);
		} catch (GenericEntityException e) {
			Debug.logError(e.getMessage(), module);
			return ServiceUtil.returnError(e.getMessage());
		}
		return result;
	}
	
	
	 
	/**
     * Creates a Person.
     * If no partyId is specified a numeric partyId is retrieved from the Party sequence.
     */
    public static Map<String, Object> createSysUser(DispatchContext ctx, Map<String, ? extends Object> context) {
        Map<String, Object> result = new HashMap<String, Object>();
        Delegator delegator = ctx.getDelegator();
        Timestamp now = UtilDateTime.nowTimestamp();
        List<GenericValue> toBeStored = new LinkedList<GenericValue>();
        Locale locale = (Locale) context.get("locale");
        // in most cases userLogin will be null, but get anyway so we can keep track of that info if it is available
        GenericValue userLogin = (GenericValue) context.get("userLogin");

        String partyId = (String) context.get("partyId");
        String roleTypeId = (String) context.get("roleTypeId");
        String description = (String) context.get("description");

        // if specified partyId starts with a number, return an error
        if (UtilValidate.isNotEmpty(partyId) && partyId.matches("\\d+")) {
            return ServiceUtil.returnError(UtilProperties.getMessage(resourceError, 
                    "party.id_is_digit", locale));
        }

        // partyId might be empty, so check it and get next seq party id if empty
        if (UtilValidate.isEmpty(partyId)) {
            try {
                partyId = delegator.getNextSeqId("Party");
            } catch (IllegalArgumentException e) {
                return ServiceUtil.returnError(UtilProperties.getMessage(resourceError, 
                        "party.id_generation_failure", locale));
            }
        }
        GenericValue party = null;

        try {
            party = EntityQuery.use(delegator).from("Party").where("partyId", partyId).queryOne();
        } catch (GenericEntityException e) {
            Debug.logWarning(e.getMessage(), module);
        }

        if (party != null) {
            if (!"PERSON".equals(party.getString("partyTypeId"))) {
                return ServiceUtil.returnError(UtilProperties.getMessage(resourceError, 
                        "person.create.party_exists_not_person_type", locale)); 
            }
        } else {
            String statusId = (String) context.get("statusId");
            if (statusId == null) {
                statusId = "PARTY_ENABLED";
            }
            Map<String, Object> newPartyMap = UtilMisc.toMap("partyId", partyId, "partyTypeId", "PERSON", "description", description, "createdDate", now, "lastModifiedDate", now, "statusId", statusId);
            if (userLogin != null) {
                newPartyMap.put("createdByUserLogin", userLogin.get("userLoginId"));
                newPartyMap.put("lastModifiedByUserLogin", userLogin.get("userLoginId"));
            }
            party = delegator.makeValue("Party", newPartyMap);
            toBeStored.add(party);
        }

        GenericValue person = null;

        try {
            person = EntityQuery.use(delegator).from("Person").where("partyId", partyId).queryOne();
        } catch (GenericEntityException e) {
            Debug.logWarning(e.getMessage(), module);
        }

        if (person != null) {
            return ServiceUtil.returnError(UtilProperties.getMessage(resourceError, 
                    "person.create.person_exists", locale)); 
        }
        GenericValue partyRole = delegator.makeValue("PartyRole", UtilMisc.toMap("partyId", partyId));
        partyRole.set("roleTypeId",roleTypeId);
        toBeStored.add(partyRole);
        person = delegator.makeValue("Person", UtilMisc.toMap("partyId", partyId));
        person.setNonPKFields(context);
        toBeStored.add(person);
        
        String userLoginId = (String) context.get("userLoginId");
        if (UtilValidate.isNotEmpty(userLoginId)) {
        	GenericValue currentUserLogin = delegator.makeValue("UserLogin", UtilMisc.toMap("userLoginId", userLoginId));
        	String currentPassword = (String) context.get("currentPassword");
        	String currentPasswordVerify = (String) context.get("currentPasswordVerify");
        	if(UtilValidate.isNotEmpty(currentPassword)&&UtilValidate.isNotEmpty(currentPasswordVerify)){
        		if(!currentPassword.equals(currentPasswordVerify)){
        			return ServiceUtil.returnError(UtilProperties.getMessage(resourceError, 
                            "UserLogin.currentPassword.not_equals", new Object[] { }, locale));
        		}
        		currentUserLogin.set("currentPassword", HashCrypt.cryptUTF8(getHashType(), null, currentPassword));
                currentUserLogin.set("enabled", "Y");
                currentUserLogin.set("partyId", partyId);
                
        	}
        	toBeStored.add(currentUserLogin);
        }
        try {
            delegator.storeAll(toBeStored);
        } catch (GenericEntityException e) {
            Debug.logWarning(e.getMessage(), module);
            return ServiceUtil.returnError(UtilProperties.getMessage(resourceError, 
                    "person.create.db_error", new Object[] { e.getMessage() }, locale)); 
        }

        result.put("partyId", partyId);
        result.put(ModelService.RESPONSE_MESSAGE, ModelService.RESPOND_SUCCESS);
        return result;
    }
    
    /**
     * uopdate a Person.
     */
    public static Map<String, Object> updateSysUser(DispatchContext ctx, Map<String, ? extends Object> context) {
        Map<String, Object> result = new HashMap<String, Object>();
        Delegator delegator = ctx.getDelegator();
        List<GenericValue> toBeStored = new LinkedList<GenericValue>();
        Locale locale = (Locale) context.get("locale");
        String partyId = (String) context.get("partyId");
        GenericValue person = null;
        try {
            person = EntityQuery.use(delegator).from("Person").where("partyId", partyId).queryOne();
        } catch (GenericEntityException e) {
            Debug.logWarning(e.getMessage(), module);
        }

        if (person == null) {
            return ServiceUtil.returnError(UtilProperties.getMessage(resourceError, 
                    "person.update.person_not_exists", locale)); 
        }

        person.setNonPKFields(context);
        toBeStored.add(person);
        String userLoginId = (String) context.get("userLoginId");
        String currentPassword = (String) context.get("currentPassword");
    	String currentPasswordVerify = (String) context.get("currentPasswordVerify");
    	
    	if(UtilValidate.isNotEmpty(userLoginId)&&UtilValidate.isEmpty(currentPassword)){
    		GenericValue currentUserLogin = delegator.makeValue("UserLogin", UtilMisc.toMap("userLoginId", userLoginId));
            toBeStored.add(currentUserLogin);
    	}
	        
	    if(UtilValidate.isNotEmpty(userLoginId)&&UtilValidate.isNotEmpty(currentPassword)&&UtilValidate.isNotEmpty(currentPasswordVerify)){
	        		if(!currentPassword.equals(currentPasswordVerify)){
	        			return ServiceUtil.returnError(UtilProperties.getMessage(resourceError, 
	                            "UserLogin.currentPassword.not_equals", new Object[] { }, locale));
	        		}
	        		
	                try {
	                	GenericValue existsUserLogin = EntityQuery.use(delegator).from("UserLogin").where("partyId", partyId,"enabled", "Y").queryFirst();
	                
	                
	                if (UtilValidate.isNotEmpty(existsUserLogin)) {
	                	String currentPasswordHashCrypt =HashCrypt.cryptUTF8(getHashType(), null, currentPassword);
	                	String currentPasswordExists=existsUserLogin.getString("currentPassword");
	                	if(!currentPasswordHashCrypt.equals(currentPasswordExists)){
	                		String userLoginIdExists=existsUserLogin.getString("userLoginId");
	                		GenericValue currentUserLogin = delegator.findOne("UserLogin", false,UtilMisc.toMap("userLoginId", userLoginIdExists));
	                		currentUserLogin.set("currentPassword", HashCrypt.cryptUTF8(getHashType(), null, currentPassword));
	                		currentUserLogin.set("enabled", "Y");
	    	                toBeStored.add(currentUserLogin);
	                	}
	                }
	                if (UtilValidate.isEmpty(existsUserLogin)) {
	        		
		        		GenericValue currentUserLogin = delegator.makeValue("UserLogin", UtilMisc.toMap("userLoginId", userLoginId));
		        		currentUserLogin.set("currentPassword", HashCrypt.cryptUTF8(getHashType(), null, currentPassword));
		                currentUserLogin.set("enabled", "Y");
		                toBeStored.add(currentUserLogin);
	                }
	                
	                
	                } catch (GenericEntityException e) {
	                    Debug.logWarning(e.getMessage(), module);
	                }
	        	}
	        
        
        
        

        try {
            delegator.storeAll(toBeStored);
        } catch (GenericEntityException e) {
            Debug.logWarning(e.getMessage(), module);
            return ServiceUtil.returnError(UtilProperties.getMessage(resourceError, 
                    "person.create.db_error", new Object[] { e.getMessage() }, locale)); 
        }

        result.put("partyId", partyId);
        result.put(ModelService.RESPONSE_MESSAGE, ModelService.RESPOND_SUCCESS);
        return result;
    }
    

    
    /*
	 * setSysPartyStatus 默认为禁用，传入可用参数，改为可用
	 */
	public static  Map<String,Object> setSysPartyStatus(DispatchContext ctx, Map<String, ? extends Object> context){
		Debug.log("setSysPartyStatus   === start");
		Map<String,Object> result = ServiceUtil.returnSuccess();
		Delegator delegator = ctx.getDelegator();
		List<GenericValue> toBeStore= FastList.newInstance();
		String statusId = (String) context.get("statusId");
		String enabled = "N";
        try {
        	String partyId = (String) context.get("partyId");
        	 if("PARTY_ENABLED".equals((String)context.get("statusId"))) {
        		  statusId = "PARTY_ENABLED";
        		  enabled = "Y";
        	 }
        	GenericValue party = EntityQuery.use(delegator).from("Party").where("partyId", partyId).queryOne();
        	
        	
        	party.set("statusId", statusId);
            toBeStore.add(party);
            
           
	        List<GenericValue> list = delegator.findByAnd("UserLogin", UtilMisc.toMap("partyId", partyId),null,false);

	            	for (GenericValue ul:list) {
	            		GenericValue existsUserLogin = delegator.makeValue("UserLogin", 
        						UtilMisc.toMap("userLoginId",ul.getString("userLoginId")));
	            		existsUserLogin.set("enabled", enabled);
		                toBeStore.add(existsUserLogin);
					}
	       delegator.storeAll(toBeStore)	;                
	             
            
			
			Debug.log("setSysPartyStatus   === end");
			result.put("partyId", partyId);
	        result.put(ModelService.RESPONSE_MESSAGE, ModelService.RESPOND_SUCCESS);
		} catch (GenericEntityException e) {
			Debug.logError(e.getMessage(), module);
			return ServiceUtil.returnError(e.getMessage());
		}
		return result;
	}
	
	    
    public static Map<String, Object> updatePassword(DispatchContext ctx, Map<String, ?> context) {
    	Map<String, Object> result = ServiceUtil.returnSuccess();
        Delegator delegator = ctx.getDelegator();
		
        //boolean useEncryption = "true".equals(UtilProperties.getPropertyValue("security.properties", "password.encrypt"));

        String userLoginId = (String) context.get("userLoginId");
        String currentPassword = (String) context.get("currentPassword");
        try {
            //if (useEncryption) {
            		GenericValue supposedSmartUser = delegator.findOne("UserLogin",false,UtilMisc.toMap("userLoginId",userLoginId));
            		supposedSmartUser.set("currentPassword", HashCrypt.cryptUTF8(getHashType(), null, currentPassword));
	                supposedSmartUser.set("passwordHint", "");
	                supposedSmartUser.set("enabled", "Y");
            	    delegator.store(supposedSmartUser);                
            //} 
        } catch (GenericEntityException e) {
            Debug.logError(e.getMessage(), module);
            return ServiceUtil.returnError(e.getMessage());
        }
     
        return result;
    }
	    public static Map<String, Object> updatePasswordForPartyId(DispatchContext ctx, Map<String, ?> context) {
	    	Map<String, Object> result = ServiceUtil.returnSuccess();
	        Delegator delegator = ctx.getDelegator();
			
	        //boolean useEncryption = "true".equals(UtilProperties.getPropertyValue("security.properties", "password.encrypt"));

	        String partyId = (String) context.get("partyId");
	        
	        String currentPassword = (String) context.get("currentPassword");

            //List toBeStore=new ArrayList();
	        
	        try {
	        	List<GenericValue> list = delegator.findByAnd("UserLogin", UtilMisc.toMap("partyId", partyId),null,false);
	        	GenericValue userLogin = EntityUtil.getFirst(list);
	        	if(UtilValidate.isNotEmpty(userLogin)){
	        		GenericValue supposedUserLogin = delegator.findOne("UserLogin", false,UtilMisc.toMap("userLoginId",userLogin.getString("userLoginId")));
	        		supposedUserLogin.set("currentPassword", HashCrypt.cryptUTF8(getHashType(), null, currentPassword));
	        		//supposedUserLogin.set("passwordHint", "");
	        		//supposedUserLogin.set("enabled", "Y");
	                delegator.store(supposedUserLogin);
	        	}
	        } catch (GenericEntityException e) {
	            Debug.logError(e.getMessage(), module);
	            return ServiceUtil.returnError(e.getMessage());
	        }
	     
	        return result;
	    }
	    
	    public static Map<String, Object> updatePasswordForPartyIdSelf(DispatchContext ctx, Map<String, ?> context) {
	    	Map<String, Object> result = ServiceUtil.returnSuccess();
	        Delegator delegator = ctx.getDelegator();
	        boolean useEncryption = "true".equals(UtilProperties.getPropertyValue("security.properties", "password.encrypt"));
	        String partyId = (String) context.get("partyId");
	        String currentPassword = (String) context.get("currentPassword");
	                                                       
	        String newPassword = (String) context.get("newPassword");
	                                            
	        Locale locale = (Locale) context.get("locale");
	        String errMsg = null;
            //List<GenericValue> toBeStore=FastList.newInstance();
	        try {
	        		List<GenericValue> list = delegator.findByAnd("UserLogin", UtilMisc.toMap("partyId", partyId),null,false);

	        		GenericValue userLogin = EntityUtil.getFirst(list);
		            if (userLogin == null) {
		                // the Username was not found
		                 errMsg = UtilProperties.getMessage(resource,"loginevents.username_not_found_reenter", locale);
		                 Map<String, Object> returnError = ServiceUtil.returnError(errMsg);
		                 returnError.put("isSuccess", "N");
		                return returnError;
		            }
		            
		            String oldPassword =userLogin.getString("currentPassword");
			        if (!checkPassword(oldPassword, useEncryption, currentPassword)) {
			        	 errMsg = UtilProperties.getMessage(resource,"原密码不正确,", locale);
			        	 Map<String, Object> returnError = ServiceUtil.returnError(errMsg);
			        	 returnError.put("isSuccess", "N");
		                return returnError;
			        }
		            if (useEncryption) {
		            	if(UtilValidate.isNotEmpty(newPassword)){
		    	        	if(UtilValidate.isNotEmpty(userLogin)){
		    	        		GenericValue supposedUserLogin = delegator.findOne("UserLogin", false,UtilMisc.toMap("userLoginId",userLogin.getString("userLoginId")));
		    	        		supposedUserLogin.set("currentPassword", HashCrypt.cryptUTF8(getHashType(), null, newPassword));
		    	                delegator.store(supposedUserLogin);
		    	        	}
		            	}             
		            } 
	        } catch (GenericEntityException e) {
	            Debug.logError(e.getMessage(), module);
	            Map<String, Object> returnError = ServiceUtil.returnError(e.getMessage());
	            returnError.put("isSuccess", "N");
	            return returnError;
	        }
	        result.put("isSuccess", "Y");
	        return result;
	    }
	    
	    
	    private static boolean checkPassword(String oldPassword, boolean useEncryption, String currentPassword) {
	        boolean passwordMatches = false;
	        if (oldPassword != null) {
	            if (useEncryption) {
	                passwordMatches = HashCrypt.comparePassword(oldPassword, getHashType(), currentPassword);
	            } else {
	                passwordMatches = oldPassword.equals(currentPassword);
	            }
	        }
	        if (!passwordMatches && "true".equals(UtilProperties.getPropertyValue("security", "password.accept.encrypted.and.plain"))) {
	            passwordMatches = currentPassword.equals(oldPassword);
	        }
	        return passwordMatches;
	    }
	    
	    
	    private static String getHashType() {
	        String hashType = UtilProperties.getPropertyValue("security.properties", "password.encrypt.hash.type");

	        if (UtilValidate.isEmpty(hashType)) {
	            Debug.logWarning("Password encrypt hash type is not specified in security.properties, use SHA", module);
	            hashType = "SHA";
	        }

	        return hashType;
	    }
	    
	    
	    /*
		 * create createSysCompany
		 */
		public static  Map<String,Object> createCoCompany(DispatchContext ctx, Map<String, ? extends Object> context){
			Debug.log("createCoCompany   === start");
			Map<String,Object> result = ServiceUtil.returnSuccess(ModelService.RESPOND_SUCCESS);
			Delegator delegator = ctx.getDelegator();
	        try {
	        	//TODO 检查参数parentId 的顶级公司id，跟userLogin所属顶级公司id 相同
	        	String partyId = delegator.getNextSeqId("Party");
	        	GenericValue party = delegator.makeValue("Party", UtilMisc.toMap("partyId", partyId));
	        	party.set("partyTypeId", "PARTY_GROUP");
	        	party.create();
	        	GenericValue partyRole = delegator.makeValue("PartyRole", UtilMisc.toMap("partyId", partyId));
	        	partyRole.set("roleTypeId", "INTERNAL_ORGANIZATIO");
	        	partyRole.create();
	        	GenericValue partyGroup = delegator.makeValue("PartyGroup", UtilMisc.toMap("partyId", partyId));
	            partyGroup.setNonPKFields(context);
	            String statusId = "PARTY_ENABLED";
	            partyGroup.set("statusId", statusId);
	            partyGroup.create();
				Debug.log("createCoCompany   === end");
				result.put("partyId", partyId);
			} catch (GenericEntityException e) {
				Debug.logError(e.getMessage(), module);
				return ServiceUtil.returnError(e.getMessage());
			}
			return result;
		}
		/*
		 * update updateCoCompany
		 */
		public static  Map<String,Object> updateCoCompany(DispatchContext ctx, Map<String, ? extends Object> context){
			Debug.log("updateCoCompany   === start");
			Map<String,Object> result = ServiceUtil.returnSuccess(ModelService.RESPOND_SUCCESS);
			Delegator delegator = ctx.getDelegator();
	        try {
	        	String partyId = (String) context.get("partyId");
				String groupCode = (String) context.get("groupCode");
				GenericValue partyGroup = EntityQuery.use(delegator).from("PartyGroup").where("partyId", partyId).queryOne();
	        	
				if(UtilValidate.isNotEmpty(groupCode)){
					String oldgroupCode = partyGroup.getString("groupCode");
		        	List<GenericValue> partyList = EntityQuery.use(delegator).from("PartyGroup").where("groupCode", groupCode).queryList();
		        	
		        	if(!groupCode.equals(oldgroupCode)){
		        		if(partyList.size()>0){
		    				return ServiceUtil.returnError("机构代码/门店ID已存在,请更换!");
		        		}
		        	}
				}
	        	
	            partyGroup.setNonPKFields(context);
	            partyGroup.store();
				
				Debug.log("updateCoCompany   === end");
				result.put("partyId", partyId);
			} catch (GenericEntityException e) {
				Debug.logError(e.getMessage(), module);
				return ServiceUtil.returnError(e.getMessage());
			}
			return result;
		}
		
		/*
		 * remove removeCoCompany
		 */
		public static  Map<String,Object> removeCoCompany(DispatchContext ctx, Map<String, ? extends Object> context){
			Debug.log("removeCoCompany   === start");
			Map<String,Object> result = ServiceUtil.returnSuccess( ModelService.RESPOND_SUCCESS);
			Delegator delegator = ctx.getDelegator();
	        try {
	        	String partyId = (String) context.get("partyId");
	        	GenericValue partyGroup = EntityQuery.use(delegator).from("PartyGroup").where("partyId", partyId).queryOne();

	        	String statusId = "PARTY_DISABLED";
	        	partyGroup.set("statusId", statusId);
	            partyGroup.store();
				
				Debug.log("removeCoCompany   === end");
				result.put("partyId", partyId);
			} catch (GenericEntityException e) {
				Debug.logError(e.getMessage(), module);
				return ServiceUtil.returnError(e.getMessage());
			}
			return result;
		}
	   
		public static Map<String, Object> createCoUser(DispatchContext ctx, Map<String, ? extends Object> context) {
	        Map<String, Object> result = new HashMap<String, Object>();
	        Delegator delegator = ctx.getDelegator();
	        LocalDispatcher dispatcher = ctx.getDispatcher();
	        Timestamp now = UtilDateTime.nowTimestamp();
	        List<GenericValue> toBeStored = new LinkedList<GenericValue>();
	        Locale locale = (Locale) context.get("locale");
	        GenericValue userLogin = (GenericValue) context.get("userLogin");

	        String partyId = (String) context.get("partyId");
	        String roleTypeId = (String) context.get("roleTypeId");
	        String groupIdList = (String) context.get("groupIdList");
	        
	        String description = (String) context.get("description");
	        if (UtilValidate.isNotEmpty(partyId) && partyId.matches("\\d+")) {
	            return ServiceUtil.returnError(UtilProperties.getMessage(resourceError, 
	                    "party.id_is_digit", locale));
	        }
	        if (UtilValidate.isEmpty(partyId)) {
	            try {
	                partyId = delegator.getNextSeqId("Party");
	            } catch (IllegalArgumentException e) {
	                return ServiceUtil.returnError(UtilProperties.getMessage(resourceError, 
	                        "party.id_generation_failure", locale));
	            }
	        }
	        GenericValue party = null;
	        try {
	            party = EntityQuery.use(delegator).from("Party").where("partyId", partyId).queryOne();
	        } catch (GenericEntityException e) {
	            Debug.logWarning(e.getMessage(), module);
	        }

	        if (party != null) {
	            if (!"PERSON".equals(party.getString("partyTypeId"))) {
	                return ServiceUtil.returnError(UtilProperties.getMessage(resourceError, 
	                        "person.create.party_exists_not_person_type", locale)); 
	            }
	        } else {
	            String statusId = (String) context.get("statusId");
	            if (statusId == null) {
	                statusId = "PARTY_ENABLED";
	            }
	            Map<String, Object> newPartyMap = UtilMisc.toMap("partyId", partyId, "partyTypeId", "PERSON", "description", description, "createdDate", now, "lastModifiedDate", now, "statusId", statusId);
	            if (userLogin != null) {
	                newPartyMap.put("createdByUserLogin", userLogin.get("userLoginId"));
	                newPartyMap.put("lastModifiedByUserLogin", userLogin.get("userLoginId"));
	            }
	            party = delegator.makeValue("Party", newPartyMap);
	            toBeStored.add(party);
	        }

	        GenericValue person = null;
	        try {
	            person = EntityQuery.use(delegator).from("Person").where("partyId", partyId).queryOne();
	        } catch (GenericEntityException e) {
	            Debug.logWarning(e.getMessage(), module);
	        }

	        if (person != null) {
	            return ServiceUtil.returnError(UtilProperties.getMessage(resourceError, 
	                    "person.create.person_exists", locale)); 
	        }
	        GenericValue partyRole = delegator.makeValue("PartyRole", UtilMisc.toMap("partyId", partyId));
	        partyRole.set("roleTypeId",roleTypeId);
	        toBeStored.add(partyRole);
	        person = delegator.makeValue("Person", UtilMisc.toMap("partyId", partyId));
	        person.setNonPKFields(context);
	        toBeStored.add(person);
	        String userLoginId = (String) context.get("userLoginId");
	        if (UtilValidate.isNotEmpty(userLoginId)) {
	        	GenericValue currentUserLogin = delegator.makeValue("UserLogin", UtilMisc.toMap("userLoginId", userLoginId));
	        	String currentPassword = (String) context.get("currentPassword");
	        	String currentPasswordVerify = (String) context.get("currentPasswordVerify");
	        	if(UtilValidate.isNotEmpty(currentPassword)&&UtilValidate.isNotEmpty(currentPasswordVerify)){
	        		if(!currentPassword.equals(currentPasswordVerify)){
	        			return ServiceUtil.returnError(UtilProperties.getMessage(resourceError, 
	                            "UserLogin.currentPassword.not_equals", new Object[] { }, locale));
	        		}
	        		currentUserLogin.set("currentPassword", HashCrypt.cryptUTF8(getHashType(), null, currentPassword));
	                currentUserLogin.set("enabled", "Y");
	                currentUserLogin.set("partyId", partyId);
	                
	        	}
	        	toBeStored.add(currentUserLogin);
	        }
	        try {
	            delegator.storeAll(toBeStored);
	            if(UtilValidate.isNotEmpty(groupIdList)) {
	            	GenericValue newUserLogin = delegator.findOne("UserLogin", UtilMisc.toMap("userLoginId", "admin"),false);
		        	
	            	dispatcher.runSync("saveSysSecurityGroupToUser", UtilMisc.toMap("partyId", partyId,"groupIdList",groupIdList,
	            			"userLogin",newUserLogin));
	            }
	        } catch (GenericEntityException e) {
	            Debug.logWarning(e.getMessage(), module);
	            return ServiceUtil.returnError(UtilProperties.getMessage(resourceError, 
	                    "person.create.db_error", new Object[] { e.getMessage() }, locale)); 
	        } catch (GenericServiceException e) {
	            Debug.logWarning(e.getMessage(), module);
	            return ServiceUtil.returnError(UtilProperties.getMessage(resourceError, 
	                    "person.create.db_error", new Object[] { e.getMessage() }, locale)); 
			}

	        result.put("partyId", partyId);
	        result.put(ModelService.RESPONSE_MESSAGE, ModelService.RESPOND_SUCCESS);
	        return result;
	    }
	    
	    /**
	     * uopdate a Person.
	     */
	    public static Map<String, Object> updateCoUser(DispatchContext ctx, Map<String, ? extends Object> context) {
	        Map<String, Object> result = new HashMap<String, Object>();
	        Delegator delegator = ctx.getDelegator();
	        List<GenericValue> toBeStored = new LinkedList<GenericValue>();
	        Locale locale = (Locale) context.get("locale");
	        String partyId = (String) context.get("partyId");
	        GenericValue person = null;
	        try {
	            person = EntityQuery.use(delegator).from("Person").where("partyId", partyId).queryOne();
	        } catch (GenericEntityException e) {
	            Debug.logWarning(e.getMessage(), module);
	        }

	        if (person == null) {
	            return ServiceUtil.returnError(UtilProperties.getMessage(resourceError, 
	                    "person.update.person_not_exists", locale)); 
	        }

	        person.setNonPKFields(context);
	        toBeStored.add(person);
	        String userLoginId = (String) context.get("userLoginId");
	        String currentPassword = (String) context.get("currentPassword");
	    	String currentPasswordVerify = (String) context.get("currentPasswordVerify");
	    	
	    	if(UtilValidate.isNotEmpty(userLoginId)&&UtilValidate.isEmpty(currentPassword)){
	    		GenericValue currentUserLogin = delegator.makeValue("UserLogin", UtilMisc.toMap("userLoginId", userLoginId));
	            toBeStored.add(currentUserLogin);
	    	}
		        
		    if(UtilValidate.isNotEmpty(userLoginId)&&UtilValidate.isNotEmpty(currentPassword)&&UtilValidate.isNotEmpty(currentPasswordVerify)){
		       if(!currentPassword.equals(currentPasswordVerify)){
		        	return ServiceUtil.returnError(UtilProperties.getMessage(resourceError, 
		                  "UserLogin.currentPassword.not_equals", new Object[] { }, locale));
		       }
		        		
		       try {
		                GenericValue existsUserLogin = EntityQuery.use(delegator).from("UserLogin").where("partyId", partyId,"enabled", "Y").queryFirst();
		                if (UtilValidate.isNotEmpty(existsUserLogin)) {
		                	String currentPasswordHashCrypt =HashCrypt.cryptUTF8(getHashType(), null, currentPassword);
		                	String currentPasswordExists=existsUserLogin.getString("currentPassword");
		                	if(!currentPasswordHashCrypt.equals(currentPasswordExists)){
		                		String userLoginIdExists=existsUserLogin.getString("userLoginId");
		                		GenericValue currentUserLogin = delegator.findOne("UserLogin", false,UtilMisc.toMap("userLoginId", userLoginIdExists));
		                		currentUserLogin.set("currentPassword", HashCrypt.cryptUTF8(getHashType(), null, currentPassword));
		                		currentUserLogin.set("enabled", "Y");
		    	                toBeStored.add(currentUserLogin);
		                	}
		                }
		                if (UtilValidate.isEmpty(existsUserLogin)) {
		        		
			        		GenericValue currentUserLogin = delegator.makeValue("UserLogin", UtilMisc.toMap("userLoginId", userLoginId));
			        		currentUserLogin.set("currentPassword", HashCrypt.cryptUTF8(getHashType(), null, currentPassword));
			                currentUserLogin.set("enabled", "Y");
			                toBeStored.add(currentUserLogin);
		                }
		                
		                
		                } catch (GenericEntityException e) {
		                    Debug.logWarning(e.getMessage(), module);
		                }
		        	}
	        try {
	            delegator.storeAll(toBeStored);
	        } catch (GenericEntityException e) {
	            Debug.logWarning(e.getMessage(), module);
	            return ServiceUtil.returnError(UtilProperties.getMessage(resourceError, 
	                    "person.create.db_error", new Object[] { e.getMessage() }, locale)); 
	        }

	        result.put("partyId", partyId);
	        result.put(ModelService.RESPONSE_MESSAGE, ModelService.RESPOND_SUCCESS);
	        return result;
	    }
	    

	    
	    /*
		 * setCoPartyStatus 默认为禁用，传入可用参数，改为可用
		 */
		public static  Map<String,Object> setCoPartyStatus(DispatchContext ctx, Map<String, ? extends Object> context){
			Debug.log("setCoPartyStatus   === start");
			Map<String,Object> result = ServiceUtil.returnSuccess();
			Delegator delegator = ctx.getDelegator();
			List<GenericValue> toBeStore=FastList.newInstance();
			String statusId = (String) context.get("statusId");
			String enabled = "N";
			
	        try {
	        	String partyId = (String) context.get("partyId");
	        	 if("PARTY_ENABLED".equals((String)context.get("statusId"))) {
	        		  statusId = "PARTY_ENABLED";
	        		  enabled = "Y";
	        	 }
	        	GenericValue party = EntityQuery.use(delegator).from("Party").where("partyId", partyId).queryOne();
	        	party.set("statusId", statusId);
	            toBeStore.add(party);
		        List<GenericValue> list = delegator.findByAnd("UserLogin", UtilMisc.toMap("partyId", partyId),null,false);

		            	for (GenericValue ul:list) {
		            		GenericValue existsUserLogin = delegator.makeValue("UserLogin", 
	        						UtilMisc.toMap("userLoginId",ul.getString("userLoginId")));
		            		existsUserLogin.set("enabled", enabled);
			                toBeStore.add(existsUserLogin);
						}
		        delegator.storeAll(toBeStore)	;                
				Debug.log("setCoPartyStatus   === end");
				result.put("partyId", partyId);
		        result.put(ModelService.RESPONSE_MESSAGE, ModelService.RESPOND_SUCCESS);
			} catch (GenericEntityException e) {
				Debug.logError(e.getMessage(), module);
				return ServiceUtil.returnError(e.getMessage());
			}
			return result;
		}

	    private static List splitCustomStringToList(String inputString, String splitChar) {
			List result = FastList.newInstance();
			if (UtilValidate.isEmpty(inputString)) {
				return result;
			}
			inputString =inputString.trim();
			String[] array = inputString.split(splitChar);
			for (int i = 0; i < array.length; i++) {
				if (UtilValidate.isNotEmpty(array[i])) {
					result.add(array[i]);
				}
			}
			return result;
		}
		
		@SuppressWarnings("unchecked")
		public static Map<String, Object> saveCoRelationShipToUser(DispatchContext ctx, Map<String, Object> context) {
	    	Map<String, Object> result = ServiceUtil.returnSuccess();
	        Debug.log("saveCoRelationShipToUser   === start");
	        Delegator delegator = ctx.getDelegator();
	    	try {
	    		String partyIdTo = (String) context.get("partyIdTo");
	    		String partyRelationshipTypeId = (String) context.get("partyRelationshipTypeId");
	    		
	    		List<String> partyIdFormList=null;
	    		if(UtilValidate.isNotEmpty(context.get("partyIdFormList"))){
	    			partyIdFormList = splitCustomStringToList((String)context.get("partyIdFormList"), ";");
	    		}
	    		Timestamp now = UtilDateTime.nowTimestamp();
	    		List<GenericValue> addRelationList=FastList.newInstance(), removeRelationList=FastList.newInstance();
	    		List<String> addRelationIdList = FastList.newInstance();	//需要新建的关联
        		List<String> removeRelationIdList = FastList.newInstance();	//需要删除的关联
        		
        		List<GenericValue> oldRelationList = FastList.newInstance();	//旧关联
	    		
        		oldRelationList.addAll(delegator.findByAnd("CoRelationship",  
    					UtilMisc.toMap("partyIdTo", partyIdTo,"partyRelationshipTypeId",partyRelationshipTypeId),UtilMisc.toList("-fromDate"),false));
	    		
        		oldRelationList = EntityUtil.filterByDate(oldRelationList);
	    		List<String> oldRelationIdList = EntityUtil.getFieldListFromEntityList(oldRelationList, "partyIdFrom", true);


	    		if(UtilValidate.isEmpty(partyIdFormList)){
	    			for (GenericValue oldRelation:oldRelationList) {
							//设置过期, 然后存储, 不删除
							oldRelation.set("thruDate", now);
							removeRelationList.add(oldRelation);
					}
	    		}else{
	    			for (String inFormId : partyIdFormList) {
						if(!oldRelationIdList.contains(inFormId)){//如果旧关联不包含当前关联
							GenericValue userRelation = delegator.makeValue("CoRelationship", 
	        						UtilMisc.toMap("partyIdTo",partyIdTo, "partyIdFrom",inFormId, "fromDate",now,
	        								"statusId","PARTY_ENABLED","partyRelationshipTypeId",partyRelationshipTypeId));
	        				addRelationList.add(userRelation);
	        				addRelationIdList.add(inFormId);
						}
					}
	        		
	        		for (String oldRelationId : oldRelationIdList) {
						if(!partyIdFormList.contains(oldRelationId)){	//如果新关联不包含旧关联ID,
							removeRelationIdList.add(oldRelationId);	//放置到删除序列中
						}
					}
	        		
	        		for (GenericValue oldRelation:oldRelationList) {
						if(removeRelationIdList.contains(oldRelation.getString("partyIdFrom"))){//如果删除序列中包含旧关联的id
							//设置过期, 然后存储, 不删除
							oldRelation.set("thruDate", now);
							removeRelationList.add(oldRelation);
						}
					}
		    		delegator.storeAll(addRelationList);
	    		}
	    		delegator.storeAll(removeRelationList);
	    	} catch (GenericEntityException e) {
	    		Debug.logError(e.getMessage(), module);
	    		return ServiceUtil.returnError("批量新增和删除用户关联失败: "+e.getMessage());
	    	} 
	    	Debug.log("saveCoRelationShipToUser   === end");
	    	return result;
	    }
		
		
		public static Map<String, Object> updateCoRelationShip(DispatchContext ctx, Map<String, Object> context) {
	    	Map<String, Object> result = ServiceUtil.returnSuccess();
	        Delegator delegator = ctx.getDelegator();
	    	try {
	    		String partyIdTo = (String) context.get("partyIdTo");
	    		String partyIdForm = (String) context.get("partyIdForm");
	    		Timestamp fromDate =  (Timestamp) context.get("fromDate");
	    		String removed =  (String) context.get("removed");
	    		Timestamp now = UtilDateTime.nowTimestamp();
	    		GenericValue entity = delegator.findOne("CoRelationship", UtilMisc.toMap("partyIdTo", partyIdTo,
	    				"partyIdForm",partyIdForm,"fromDate",fromDate), false);
	    		entity.setNonPKFields(context);
	    		if(UtilValidate.isNotEmpty(removed)){
	    			if(removed.equals("Y")){
		    			entity.set("thruDate", now);
	    			}
	    		}
	    		entity.store();
	    	} catch (GenericEntityException e) {
	    		Debug.logError(e.getMessage(), module);
	    		return ServiceUtil.returnError("批量新增和删除用户关联失败: "+e.getMessage());
	    	} 
	    	return result;
	    }
		
		
		public static Map<String, Object> createZebraUser(DispatchContext ctx, Map<String, ? extends Object> context) {
	        Map<String, Object> result = new HashMap<String, Object>();
	        Delegator delegator = ctx.getDelegator();
	        LocalDispatcher dispatcher = ctx.getDispatcher();
	        Timestamp now = UtilDateTime.nowTimestamp();
	        List<GenericValue> toBeStored = new LinkedList<GenericValue>();
	        Locale locale = (Locale) context.get("locale");

	        String partyId = (String) context.get("partyId");
	        String roleTypeId = (String) context.get("roleTypeId");
	        String groupIdList = (String) context.get("groupIdList");
	        
	        String description = (String) context.get("description");
	        if (UtilValidate.isNotEmpty(partyId) && partyId.matches("\\d+")) {
	            return ServiceUtil.returnError(UtilProperties.getMessage(resourceError, 
	                    "party.id_is_digit", locale));
	        }
	        if (UtilValidate.isEmpty(partyId)) {
	            try {
	                partyId = delegator.getNextSeqId("Party");
	            } catch (IllegalArgumentException e) {
	                return ServiceUtil.returnError(UtilProperties.getMessage(resourceError, 
	                        "party.id_generation_failure", locale));
	            }
	        }
	        GenericValue party = null;
	        try {
	            party = EntityQuery.use(delegator).from("Party").where("partyId", partyId).queryOne();
	        } catch (GenericEntityException e) {
	            Debug.logWarning(e.getMessage(), module);
	        }

	        if (party != null) {
	            if (!"PERSON".equals(party.getString("partyTypeId"))) {
	                return ServiceUtil.returnError(UtilProperties.getMessage(resourceError, 
	                        "person.create.party_exists_not_person_type", locale)); 
	            }
	        } else {
	            String statusId = (String) context.get("statusId");
	            if (statusId == null) {
	                statusId = "PARTY_ENABLED";
	            }
	            Map<String, Object> newPartyMap = UtilMisc.toMap("partyId", partyId, "partyTypeId", "PERSON", "description", description, "createdDate", now, "lastModifiedDate", now, "statusId", statusId);
	            party = delegator.makeValue("Party", newPartyMap);
	            toBeStored.add(party);
	        }

	        GenericValue person = null;
	        try {
	            person = EntityQuery.use(delegator).from("Person").where("partyId", partyId).queryOne();
	        } catch (GenericEntityException e) {
	            Debug.logWarning(e.getMessage(), module);
	        }

	        if (person != null) {
	            return ServiceUtil.returnError(UtilProperties.getMessage(resourceError, 
	                    "person.create.person_exists", locale)); 
	        }
	        GenericValue partyRole = delegator.makeValue("PartyRole", UtilMisc.toMap("partyId", partyId));
	        partyRole.set("roleTypeId",roleTypeId);
	        toBeStored.add(partyRole);
	        person = delegator.makeValue("Person", UtilMisc.toMap("partyId", partyId));
	        person.setNonPKFields(context);
	        toBeStored.add(person);
	        String userLoginId = (String) context.get("userLoginId");
	        if (UtilValidate.isNotEmpty(userLoginId)) {
	        	GenericValue currentUserLogin = delegator.makeValue("UserLogin", UtilMisc.toMap("userLoginId", userLoginId));
	        	String currentPassword = (String) context.get("currentPassword");
	        	String currentPasswordVerify = (String) context.get("currentPasswordVerify");
	        	if(UtilValidate.isNotEmpty(currentPassword)&&UtilValidate.isNotEmpty(currentPasswordVerify)){
	        		if(!currentPassword.equals(currentPasswordVerify)){
	        			return ServiceUtil.returnError(UtilProperties.getMessage(resourceError, 
	                            "UserLogin.currentPassword.not_equals", new Object[] { }, locale));
	        		}
	        		currentUserLogin.set("currentPassword", HashCrypt.cryptUTF8(getHashType(), null, currentPassword));
	                currentUserLogin.set("enabled", "Y");
	                currentUserLogin.set("partyId", partyId);
	                
	        	}
	        	toBeStored.add(currentUserLogin);
	        }
	        try {
	            delegator.storeAll(toBeStored);
	            if(UtilValidate.isNotEmpty(groupIdList)) {
	            	GenericValue newUserLogin = delegator.findOne("UserLogin", UtilMisc.toMap("userLoginId", "admin"),false);
	            	dispatcher.runSync("saveSysSecurityGroupToUser", UtilMisc.toMap("partyId", partyId,"groupIdList",groupIdList,
	            			"userLogin",newUserLogin));
	            }
	        } catch (GenericEntityException e) {
	            Debug.logWarning(e.getMessage(), module);
	            return ServiceUtil.returnError(UtilProperties.getMessage(resourceError, 
	                    "person.create.db_error", new Object[] { e.getMessage() }, locale)); 
	        } catch (GenericServiceException e) {
	            Debug.logWarning(e.getMessage(), module);
	            return ServiceUtil.returnError(UtilProperties.getMessage(resourceError, 
	                    "person.create.db_error", new Object[] { e.getMessage() }, locale)); 
			}

	        result.put("partyId", partyId);
	        result.put(ModelService.RESPONSE_MESSAGE, ModelService.RESPOND_SUCCESS);
	        return result;
	    }
		
}
